package com.example.capsule_netty.netty;

import com.example.capsule_netty.configuration.Constant;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author: zhuzhiming
 * @Date: 2022/4/27 19:23
 */

@Slf4j
public class NettyManager {

    private NioEventLoopGroup bossGroup;
    private NioEventLoopGroup workerGroup;
    private ServerBootstrap serverBootstrap;
    private ChannelFuture channelFuture;
    private Channel channel;

    public NettyManager() {
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
        serverBootstrap = new ServerBootstrap();
    }

    public void doStart(ChannelFutureListener listener) {

        new Thread(() -> {
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new NettyInitializer());
            try {
                channelFuture = serverBootstrap.bind(Constant.PORT).sync().addListener(listener);
                channel = channelFuture.channel();
                channel.closeFuture().sync();
            } catch (InterruptedException e) {
                log.error("netty服务器启动失败原因!!!------>" + e);
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }

        }).start();

    }


}
